<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract {

    private $_controller =  'index'; 
    private $_action = 'index';

    public function __construct() {
        $acl = new Zend_Acl();
        // roles
	$acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'));
        
        //resources
        $acl->add(new Zend_Acl_Resource('auth'));
        $acl->add(new Zend_Acl_Resource('index'));
        $acl->add(new Zend_Acl_Resource('registration'));
        $acl->add(new Zend_Acl_Resource('admin'));
        $acl->add(new Zend_Acl_Resource('profile'));
        $acl->add(new Zend_Acl_Resource('rates'));
        $acl->add(new Zend_Acl_Resource('routes'));
        $acl->add(new Zend_Acl_Resource('markers'));
        $acl->add(new Zend_Acl_Resource('requisites'));
        $acl->add(new Zend_Acl_Resource('gps'));
        $acl->add(new Zend_Acl_Resource('other'));
        
        //permission
        $acl->deny();
        $acl->allow('admin', null);
        
        //Guest rights
        $acl->allow('guest', 'auth');
	$acl->allow('guest', 'index');
	$acl->allow('guest', 'registration');
        $acl->allow('guest', 'other');

        //устанавливаем права для "User"
        $acl->allow('user', 'profile');
        $acl->allow('user', 'routes');
        $acl->allow('user', 'gps');
        $acl->allow('user', 'other');               

        Zend_Registry::set('acl', $acl);
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $auth = Zend_Auth::getInstance();
        $acl = Zend_Registry::get('acl');

        if ($auth->hasIdentity()) {
            $role = $auth->getIdentity()->role;
        } else {
            $role = 'guest';
        }
        if (!$acl->hasRole($role)) {
            $role = 'guest';
        }
        $controller = $request->controller;
        $action = $request->action;

        if (!$acl->has($controller)) {
            $controller = null;
        }

        if (!$acl->isAllowed($role, $controller, $action)) {
            $request->setControllerName($this->_controller);
            $request->setActionName($this->_action);
        }
    }
}

?>
